package com.campus.campusdelivery.repository;

import com.campus.campusdelivery.entity.MenuItem;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MenuItemRepository extends JpaRepository<MenuItem, Long> {
    
    List<MenuItem> findByMerchantId(Long merchantId);
    
    List<MenuItem> findByMerchantIdAndAvailable(Long merchantId, Boolean available);
    
    List<MenuItem> findByCategoryId(Long categoryId);
    
    // 新增带分页的分类查询方法
    Page<MenuItem> findByCategoryId(Long categoryId, Pageable pageable);
    
    List<MenuItem> findByMerchantIdAndCategoryId(Long merchantId, Long categoryId);
    
    @Query("SELECT mi FROM MenuItem mi WHERE mi.merchant.id = :merchantId AND mi.available = true ORDER BY mi.sortOrder ASC")
    List<MenuItem> findAvailableMenuItemsByMerchant(@Param("merchantId") Long merchantId);
    
    @Query("SELECT mi FROM MenuItem mi WHERE mi.name LIKE %:keyword% OR mi.description LIKE %:keyword%")
    Page<MenuItem> findByKeyword(@Param("keyword") String keyword, Pageable pageable);
    
    @Query("SELECT mi FROM MenuItem mi WHERE mi.merchant.id = :merchantId AND (mi.name LIKE %:keyword% OR mi.description LIKE %:keyword%)")
    Page<MenuItem> findByMerchantAndKeyword(@Param("merchantId") Long merchantId, 
                                          @Param("keyword") String keyword, 
                                          Pageable pageable);
    
    @Query("SELECT COUNT(mi) FROM MenuItem mi WHERE mi.merchant.id = :merchantId")
    long countByMerchantId(@Param("merchantId") Long merchantId);
}
